import { trim } from "lodash";
import React, { useState } from "react";
import PropTypes from "prop-types";
import Menu from "antd/lib/menu";
import Radio from 'antd/lib/radio';
import Dropdown from "antd/lib/dropdown";
import Button from "antd/lib/button";
import Widget from "./Widget";
import { Dashboard } from "@/services/dashboard";
import { DashboardComponent } from "@/pages/dashboards/DashboardPage";
import { DownOutlined  } from '@ant-design/icons';
import  * as Icons from '@ant-design/icons';
import useDashboard from "@/pages/dashboards/hooks/useDashboard";
import { replaceUrlParameter } from "@redash/viz/lib/lib/DateRangeParameter";
import HtmlContent from "@redash/viz/lib/components/HtmlContent";

function ContainerWidgetHeader({ widget, dashboardObj, onRefresh }) {
  const title = replaceUrlParameter(widget.getWidgetOptions("widget_title")) || dashboardObj.name;
  const showPortal = window.location.search.includes("show_portal") && localStorage.getItem('colorstyle_titlecolor');
  const widgetBgTransparent = widget.getWidgetOptions("widget_bgtransparent"); 

  const muiltView = (widget.getWidgetOptions("toggle_dashboard1") || widget.getWidgetOptions("toggle_dashboard2")
    || widget.getWidgetOptions("toggle_dashboard3") || widget.getWidgetOptions("toggle_dashboard4") 
    || widget.getWidgetOptions("toggle_dashboard5"))

  const menu =  muiltView && (widget.getWidgetOptions("toggle_view_style") === "Radio" ? (
    <Radio.Group defaultValue={dashboardObj.id} buttonStyle="outline"
      onChange={e => onRefresh(parseInt(e.target.value))}
    >
      {["1","2","3","4","5"].map(item => {
        const newIcon = Icons[widget.getWidgetOptions("toggle_dashboard"  + item + "_icon")]
        return widget.getWidgetOptions("toggle_dashboard" + item) && (    
          <Radio.Button value={widget.getWidgetOptions("toggle_dashboard" + item)}
            style={showPortal ? {backgroundColor: "#00000000", color: localStorage.getItem("colorstyle_color")} : null}
          >
            {newIcon && React.createElement(newIcon)}
            {widget.getWidgetOptions("toggle_dashboard" + item + "_title") || "菜单" + item}
          </Radio.Button>
        );}
      )}
    </Radio.Group>
  ):(
    <Menu className='widget-menu' selectedKeys={[dashboardObj.id.toString()]} 
      onClick={e => onRefresh(parseInt(e.key))}
      style={showPortal && widget.getWidgetOptions("toggle_view_style") === "Menu" ? {background: "#00000000", color: localStorage.getItem('colorstyle_titlecolor')} : null}
      mode={widget.getWidgetOptions("toggle_view_style") === "Menu" ? "horizontal" : "vertical"}
    >
    {["1","2","3","4","5"].map(item => {
      const newIcon = Icons[widget.getWidgetOptions("toggle_dashboard"  + item + "_icon")]
      return widget.getWidgetOptions("toggle_dashboard" + item) && (    
        <Menu.Item key={widget.getWidgetOptions("toggle_dashboard" + item)}>
          {newIcon && React.createElement(newIcon)}
          {widget.getWidgetOptions("toggle_dashboard" + item + "_title") || "菜单" + item}
        </Menu.Item>
      );}
    )}
    </Menu>
  ))

  return (!!trim(title) || menu) && (
    <div className="t-header widget clearfix"
      style={showPortal ? {
        background: (widgetBgTransparent || !trim(title)) ? 'transparent' : localStorage.getItem('colorstyle_titleback'), 
        color: localStorage.getItem('colorstyle_titlecolor'),
        height: '40px',
      } : {height: '40px'}}
    >
      <div className="th-title">  
        <div style={!!widget.getWidgetOptions("title_center") ? {textAlign:'center',float: 'middle'} : {float: 'left'}}>
          <span style={showPortal ? {color: localStorage.getItem('colorstyle_titlecolor')} : null}>
            <HtmlContent>{title}</HtmlContent>
          </span>
        </div>
        <div style={{float: !!title.trim() ? 'right' : 'left', marginRight:'8px', marginTop: '-7px'}}>
          {widget.getWidgetOptions("toggle_view_style") === "Radio" && menu}
          {widget.getWidgetOptions("toggle_view_style") === "Menu" && menu}
          {menu && (!widget.getWidgetOptions("toggle_view_style") || widget.getWidgetOptions("toggle_view_style") === "Dropdown") && (
            <Dropdown overlay={menu}>
            <Button style={showPortal ? {color: localStorage.getItem('colorstyle_titlecolor')} : null}>
              {widget.getWidgetOptions("toggle_view_title") || "请选择"} <DownOutlined  />
            </Button>
            </Dropdown>
          )}
        </div>
      </div>
    </div>
  );
}

function ContainerWidget(props) {
  const { widget } = props;
  const [refreshStartedAt, setRefreshStartedAt] = useState(widget.refreshStartedAt);
  const [dashboardObj, setDashboardObj] = useState(props.containerDashboardObj);
  const [isReady, setIsReady] = useState(true);
  const widgetMargins = widget.getWidgetOptions("widget_margins") || 0;
  const widgetRadius = widget.getWidgetOptions("widget_radius") || 0;
  const widgetHidePopMenus = props.widgetHidePopMenus || widget.getWidgetOptions("widget_hidepopmenus") || false;
  const dashboardOptions = useDashboard(dashboardObj, true);

  if (!!!refreshStartedAt && !!widget.refreshStartedAt) {
    setRefreshStartedAt(widget.refreshStartedAt);
  } else if (!!refreshStartedAt && !!widget.refreshStartedAt) {
    if (refreshStartedAt.isBefore(widget.refreshStartedAt)) {
      setRefreshStartedAt(widget.refreshStartedAt);
      onRefreshDashboard();
    }
  }

  function onRefreshDashboard() {
    if (dashboardOptions) dashboardOptions.refreshDashboard(true);
  }

  function onRefresh(dashboard_id) {
    if (!dashboard_id || dashboard_id === 0 || dashboard_id === dashboardOptions.dashboard_id ){
      onRefreshDashboard();
    } else {
      setIsReady(false);
      Dashboard.get({ id: dashboard_id })
      .then(dashboardData => {
        setDashboardObj(dashboardData);
        setIsReady(true);
      })
      .catch();
    }
  }
  
  if (!widget.width && !isReady) {
    return null;
  }

  return (    
    <Widget 
      {...props} 
      className={!!widget.getWidgetOptions("widget_noscroll") ? "widget-text noscrollbox" : "widget-text scrollbox"}
      header={<ContainerWidgetHeader widget={widget} dashboardObj={dashboardObj} onRefresh={onRefresh} />
      }
    >
      <DashboardComponent
        dashboard={dashboardObj} 
        widgetMargins={widgetMargins}
        widgetRadius={widgetRadius}
        widgetHidePopMenus={widgetHidePopMenus}
        isContainer={true}
        containerWidgetHeight={widget.options && widget.options.position.sizeY}
        containerWidgetWidth={widget.options && widget.options.position.size}
        hide_header={true}
        hide_parameters={widget.getWidgetOptions("hide_parameters") || false}
      />
    </Widget>
  );
}

ContainerWidget.propTypes = {
  widget: PropTypes.object.isRequired, // eslint-disable-line react/forbid-prop-types
};

export default ContainerWidget;
